package com.inwavetech.os.sync;

import android.content.Context;

import com.inwavetech.os.entity.Os;
import com.inwavetech.os.util.DaoHelper;
import com.inwavetech.os.util.SessionManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.Collection;

/**
 * Send updated os to the server
 */
public class OsSyncer {
    private final OsSender osSender;
    private final Dao<Os,?> osDao;

    public OsSyncer(Context context) throws OsSyncerException {
        DaoHelper daoHelper = new DaoHelper(context);
        SessionManager sessionManager = new SessionManager(context, daoHelper);

        if (!sessionManager.isLoggedIn()) {
            throw new OsSyncerException("user not logged in");
        }

        osDao = daoHelper.getDao(Os.class);
        osSender = new OsSender(context, sessionManager);
    }

    public void syncFinishedOs() throws SQLException, OsSender.OsSenderException {
        Collection<Os> osCol = getFinishedOses();

        for (Os os: osCol) {
            osSender.send(os);
            os.send_to_server = false;
            osDao.update(os);
        }
    }

    public static class OsSyncerException extends Exception {
        public OsSyncerException(String m) {
            super(m);
        }
    }

    private Collection<Os> getFinishedOses() throws SQLException {
        QueryBuilder qb = osDao.queryBuilder();

        qb.where().eq("send_to_server", true);
        qb.orderBy("updated_at", false);

        return qb.query();
    }
}
